const constants = require("../data/constants");
const sip = require("sip");
const log4js = require('../data/log');
const logger = log4js.getLogger('sip');

module.exports={
    /**
     * 去掉没有用的引号
     * @param input
     * @returns {string}
     */
    trim: function (input) {
        return (input || '').replace(/"/g, '');
    },
    generateVia(protocol, params, via0) {
        const via = Object.assign({
            protocol,
            host: constants.sip.option.sip_command_host,
            port: constants.sip.option.sip_command_port,
            version: constants.sip.version
        }, via0);

        if (params) {
            via.params = Object.assign({}, params);
        } else {
            via.params = {branch: sip.generateBranch(),rport: null};
        }
        return [via];
    },
    /**
     * 生成uri地址
     * @param {*} deviceid 设备信息
     * @param {*} channel 通道号，为空表示和deviceid一致
     * @param {*} protocol 协议，默认UDP
     * @param {*} host 目标主机
     * @param {*} port 目标端口
     */
    generateUri (deviceid, channel, protocol, host, port) {
        if (deviceid) {
            let uri;
            if (channel) {
                uri = `sip:${channel}@${host}:${port}`;
            } else {
                uri = `sip:${deviceid}@${host}:${port}`;
            }

            if (protocol && protocol.toLowerCase() === 'tcp') {
                uri = uri + ';transport=TCP';
            }
            return uri;
        } else {
            logger.error('deviceid 为空');
            return null;
        }
    },
    /**
     * 生成contact字段值
     */
    generateContact() {
        return [{
            uri:
                'sip:' + constants.sip.option.sip_command_account + '@' + constants.sip.option.sip_command_host + ':' + constants.sip.option.sip_command_port
        }];
    },
    fixHost(input) {
        return input.replace('[::ffff:', '').replace(']', '');
    }
}
